//
//  ST_AIMycenterLayout.swift
//  btvideo
//
//  Created by mac on 2020/5/25.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit


class ST_AIMycenterLayout: UICollectionViewFlowLayout {
    
    static let height = (35+5+287+statusBarHeight - 48 + 80)

    static let stickOffset = 80.cgFloat
    
    // MARK: - Collection View Flow Layout Methods

    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        guard let layoutAttributes = super.layoutAttributesForElements(in: rect) else { return nil }

        // Helpers
        let sectionsToAdd = NSMutableIndexSet()
        var newLayoutAttributes = [UICollectionViewLayoutAttributes]()

        for layoutAttributesSet in layoutAttributes {
            if layoutAttributesSet.representedElementCategory == .cell {
                // Add Layout Attributes
                newLayoutAttributes.append(layoutAttributesSet)

                // Update Sections to Add
                sectionsToAdd.add(layoutAttributesSet.indexPath.section)

            } else if layoutAttributesSet.representedElementCategory == .supplementaryView {
                // Update Sections to Add
                sectionsToAdd.add(layoutAttributesSet.indexPath.section)
            }
        }

        for section in sectionsToAdd {
            let indexPath = IndexPath(item: 0, section: section)

            if let sectionAttributes = self.layoutAttributesForSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, at: indexPath) {
                newLayoutAttributes.append(sectionAttributes)
            }
        }

        return newLayoutAttributes
    }

    override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        
        guard let layoutAttributes = super.layoutAttributesForSupplementaryView(ofKind: elementKind, at: indexPath) else { return nil }

        guard let collectionView = collectionView else { return layoutAttributes }

        // Helpers
        let contentOffsetY = collectionView.contentOffset.y
        var frameForSupplementaryView = layoutAttributes.frame

        //    不滑动
        if contentOffsetY > ST_AIMycenterLayout.height - ST_AIMycenterLayout.stickOffset{
              
              let y = contentOffsetY + ST_AIMycenterLayout.stickOffset - ST_AIMycenterLayout.height
              
                frameForSupplementaryView = CGRect.init(x: 0, y: y, width: frameForSupplementaryView.width, height: frameForSupplementaryView.height)
        }
        
        layoutAttributes.frame = frameForSupplementaryView

        layoutAttributes.zIndex = 10
        
        return layoutAttributes
    }

}
